import ApiV1WxSessionPageList_post from "@/api/ApiV1WxSessionPageList_post"
import type { IRawSession } from "@/chatlog_types/IRawSession"
import { ContactType } from "@/constants/ContactType"
import { friendly_datetime } from "@/utils/friendly_time_text"
import dayjs, { Dayjs } from "dayjs"
import { pinyin } from "pinyin-pro"
import type { ISessionItem } from "./ISessionItem"
import { IMessage } from "../chat"

export function session_adapter(src: IRawSession, now: Dayjs): ISessionItem {
  const text = src.nickName ?? src.userName
  const py1 = pinyin(text, { pattern: 'pinyin' }).replace(/\s/g, '')
  const py2 = pinyin(text, { pattern: 'first' }).replace(/\s/g, '')
  const time = dayjs(src.nTime)
  const ct = ContactType.guess_contact_type(src.userName)
  const ret: ISessionItem = {
    ...src,
    nickName: src.nickName || src.userName,
    py1: py1,
    py2: py2,
    datetime: friendly_datetime(now, time),
    timestamp: time.unix(),
    contact_type: ct,
    contact_type_name: ContactType.label(ct) ?? ct,
    raw: { ...src }
  }
  return ret;
}
export function session_adapter2(src: ApiV1WxSessionPageList_post.RespData, now: Dayjs): ISessionItem {
  return session_adapter({
    ...src,
    nOrder: src.order ?? -1,
    userName: src.userName ?? 'no userName',
    nickName: src.nickName ?? '',
    content: src.content ?? '',
    nTime: src.time ?? dayjs(0).format(),
    src: src,
  }, now)
}
export function session_adapter3(src: IMessage, now: Dayjs): ISessionItem {
  const raw: IRawSession = {
    nOrder: dayjs(src.raw?.time).date(),
    userName: src.raw?.sender ?? '',
    nickName: src.raw?.senderName ?? '',
    content: src.raw?.content ?? '',
    nTime: dayjs(src.raw?.time).format(),
    account: src.raw?.account,
    src: src,
  }
  return session_adapter(raw, now)
}